<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="/pages/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>采购退货</title>
<script type="text/javascript">
$(function () {
	

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    //初始化提示框的位置：top-center，bottom-left，bottom-right
    toastr.options.positionClass = 'toast-top-center';
    
    $('#btn_add').click(function () {
    	
    	window.location.href='${pageContext.request.contextPath }/pages/cb/plan_insert.jsp';
    	
    });
    $('#btn_edit').click(function () {
    	var row=$.map($("#tb_departments").bootstrapTable('getSelections'),function(row){
    		return row ;
    	});
    	if (row.length != 1) {
    		toastr.warning('请选择一条数据!');
    	}else{
    		if(row[0].remark6 != 0){
    			toastr.warning('请选择未提交审批的数据!');
    		}else{
	    		window.location.href='${pageContext.request.contextPath }/plan/toupdata.do?id='+row[0].id;
    		}
    	}
    	
    });

	$('#tb_departments').on('click-row.bs.table',function (e, row, element) {
        $("#id").val(row.plannumber);
		/* $('#tb_tables').bootstrapTable('destroy'); */ 
    	$('#tb_tables').bootstrapTable('refresh');
    });



    /**
     * 启动流程
     */
    $('#btn_depty').click(function () {

        var row = $("#tb_departments").bootstrapTable('getSelections');

        if (row.length !=  1) {
            toastr.warning('请选择一条有效数据');
            return;
        }
        
        if(row[0].remark6 == 1 || row[0].remark6 == 2) {
        	toastr.warning('已提交审核');
            return;
        }
        
        

        Ewin.confirm({message: "确认提交审核吗？"}).on(function (e) {

            if (e) {
                $.ajax({
                    type:'post',
                    data:"pid="+row[0].id,
                    url:'${pageContext.request.contextPath}/submit/planStartApply.do',
                    success:function (data) {
                        var result=eval("("+data+")");
                        if (result.success) {
                            $('#tb_departments').bootstrapTable('refresh');
                            toastr.success("提交成功");
                        } else {
                            toastr.error('提交失败，请联系管理员!');
                        }
                    }
                });
                return;
            }


        })
    });
    
});


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_departments').bootstrapTable({
            url: '${pageContext.request.contextPath }/plan/planList.do',         //请求后台的URL（*）
            method: 'GET',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: true,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 528,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            columns: [{
                checkbox: true
            },{
                field: 'id',
                title: '采购计划id',
                visible: false
            },{
                field: 'plannumber',
                title: '采购计划单号'
            },{
            	field: 'datetime',
                title: '采购计划时间'
            },{
            	field: 'remark6',
                title: '审批状态',
                formatter:function (value,row,index) {

            	    var result = "";

                    if (row.remark6 == 0) {
                        result = "未审核"
                    }if (row.remark6 == 1){
                        result = "审核中"
                    }if (row.remark6 == 2){
                        result = "审核完成"
                    }if (row.remark6 == 3){
                        result = "审核未通过"
                    }

                    return result;
                }
            }]
        });
        
         $('#tb_tables').bootstrapTable({
        	url: '${pageContext.request.contextPath }/PlanDetailed/PlanDetailedList.do',
        	method: 'GET',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            cache: true,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 468,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: oTableInit.queryParam,//传递参数（*）
            columns: [{
                field: 'id',
                title: 'id',
                visible: false
            }, {
                field: 'plannumber',
                title: '采购计划单号'
            }, {
                field: 'materiel.name',
                title: '物料名称',
                formatter:function(value,row,index){
                	if(row.materiel == null || row.materiel == ""){return "";}
                	else{return row.materiel.name;}
                }, 
            }, {
                field: 'materiel.materialmodel',
                title: '物料型号',
                formatter:function(value,row,index){
                	if(row.materiel == null || row.materiel == ""){return "";}
                	else{return row.materiel.materialmodel;}
                }, 
            }, {
                field: 'materiel.color',
                title: '颜色',
                formatter:function(value,row,index){
                	if(row.materiel == null || row.materiel == ""){return "";}
                	else{return row.materiel.color;}
                },
            }, {
            	field: 'productiontotal',
                title: '生产需求数量' ,
                formatter:function(value,row,index){
                	if(row.materiel == null || row.materiel == ""){return "";}
                	else if(row.materialStock == null || row.materialStock == ""){return parseInt(row.plantotal)+0-parseInt(row.materiel.remark7);}
                	else{
                    return parseInt(row.plantotal)+parseInt(row.materialStock.wnum)-parseInt(row.materiel.remark7);
                	}
                },  
            },{
            	field: 'materialStock.wnum',
                title: '库存数量',
                formatter:function(value,row,index){
                	if(row.materialStock == null || row.materialStock == ""){return 0;}
                	else{return row.materialStock.wnum;}
                }, 
            },{
            	field: 'materiel.remark7',
                title: '最低安全库存量',
                formatter:function(value,row,index){
                	if(row.materiel == null || row.materiel == ""){return "";}
                	else{return row.materiel.remark7;}
                },
            },{
            	field: 'plantotal',
                title: '采购计划量'
            }]
        }); 
    };

    
    
    
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            starPrdate:$.trim($('#starprdate').val()), 
            endPrdate:$.trim($('#endprdate').val()), 
            planNumber:$.trim($('#plannumberTJ').val()),  
        };  
        return temp;
    };
    //得到查询的参数
    oTableInit.queryParam = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            planNumber:$.trim($('#id').val()), 
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};
function seach() {
	$('#tb_departments').bootstrapTable('refresh'); 
}
function clearSearch() {
	//清空表单
	document.getElementById("formSearch").reset(); 
}
</script>
<script type="text/javascript">
 $(function () {
	$(".form_datetime").datetimepicker({
	 format: "yyyy-mm-dd",
	 autoclose: true,
	 todayBtn: true,
	 todayHighlight: true,
	 showMeridian: true,
	 pickerPosition: "bottom-left",
	 language: 'zh-CN',//中文，需要引用zh-CN.js包
	 startView: 2,//月视图
	 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
	 });
 });
</script>
<style type="text/css">
.my-container {
    float: left;
    display: inline-block;
    margin-right:30px;
}

.myLabel-content ,.myText-content,.myBtn-content{
    float: left;
    display: inline-block;
    margin-left: 10px;
}
.myLabel-content,.myText-content input[type='text'],.myBtn-content .btn {
    height: 30px;
    font-size: 12px;
}
.myBtn-content .btn {
    margin-bottom: 10px;
}
</style>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
		<div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                	<div class="form-group" >
                        <label class="control-label col-sm-1" for="txt_search_departmentname">日期:</label>
                        <div class="col-sm-1">
                            <select id="txt_search_departmentname" onchange="selectTime()" class="selectpicker show-tick form-control"  data-live-search="false">
	                         	<option value="0">所有时间</option>
	                         	<option value="1">最近一天</option>
	                         	<option value="7">最近一星期</option>
	                         	<option value="30">最近一个月</option>
                         	</select>
                         	<script type="text/javascript">
                         		function selectTime() {
                         			var dom=$('#txt_search_departmentname').selectpicker('val');
                         			var curDate = new Date(); 
                         			$("#endprdate").val(FormatDate(curDate));
                         			var endtime = null;
                         			if (dom > 7) {
                         				endtime = curDate.setMonth(curDate.getMonth()-1);
									}else{
										if (dom == 0) {
											$("#endprdate").val(null);
										} else {
											endtime = new Date(curDate.getTime() - dom*24*60*60*1000); //前一天
										}
									}
                         			if (endtime == null) {
	                         			$("#starprdate").val(endtime);
									} else {
                         				$("#starprdate").val(FormatDate(endtime));
									}
								}
                         		function add0(m){return m<10?'0'+m:m }
                         		function FormatDate (strTime) {
                         		    var date = new Date(strTime);
                         		    return date.getFullYear()+"-"+add0((date.getMonth()+1))+"-"+add0(date.getDate());
                         		}
                         		$(document).ready(function(){
                       			  $(".timeduan").change(function(){
                       				var end = $.trim($('#endprdate').val()) ;
                       				var star =$.trim($('#starprdate').val()); 
                       				if (end != null && end != "" && star != null && star != "") {
	                       				if (end < star) {
	                       					toastr.warning('开始时间小于结束时间,按此条件将查不到数据!');
										}
									}
                       			  });
                       			});
                         	</script>
                        </div>
                        <label class="control-label col-sm-1" for="txt_search_statu" style="width: 30px;">从</label> 
                        <div class="col-sm-2" style="width: 236px;/* padding-left: 0px;padding-right: 0px; */">
                        	<input class="form_datetime form-control timeduan" type="text" id="starprdate" name="starprdate" readonly >
                        </div>
                        <label class="control-label col-sm-1" for="txt_search_statu" style="width: 30px;padding-left: 0px;">至</label> 
                        <div class="col-sm-2" style="width: 236px;/* padding-left: 0px;padding-right: 0px; */">
                        	<input class="form_datetime form-control timeduan"  type="text" id="endprdate" name="endprdate" readonly >
                        </div>
						<label class="control-label col-sm-1 " for="txt_search_departmentname">采购计划单号<!-- 客户 -->:</label>
                        <div class="col-sm-1">
                        	<input class="form-control"  type="text" id="plannumberTJ" name="plannumberTJ">
	                         
	                         <!-- <select id="suppliername" name="suppliername" class="show-tick form-control selectpicker"  data-live-search="false">
		                         <option value="">所有客户</option>
	                         </select>
                         	 <script type="text/javascript">
				                $(function(){
				                    $.ajax({
						                type: "post",
						                url: "${pageContext.request.contextPath }/supplier/all.do",
						                dataType: 'JSON',
						                success: function (data) {
						                      //设置下拉列表中的值的属性
						                      for ( var i = 0; i < data.length; i++) {
							                        //增加下拉列表。
							                        $("#suppliername").append("<option>"+data[i].suppliername+"</option>");
											 }
						                     //必须执行，否则数据添加失败
						                     $('#suppliername').selectpicker('refresh'); 
						                     //$('#suppliername').selectpicker('render'); 
						                }
						            });
				                });
				            	//思路如上。你可以将点击时将文本框中值传到后台，后台返回数据后，在将数据存入下拉列表对象中。
				        	</script> -->
                        </div>
                         <div>
		                	<button type="button" style="margin-left:50px" id="btn_query1" class="btn btn-primary" onclick="seach()">查询</button>
		                	<button type="button" style="margin-left:50px" id="btn_query2" class="btn btn-primary" onclick="clearSearch()">清除</button>
		                 </div>
                	</div>	
                </form>
            </div>
        </div> 


        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default" onclick="doDelete()">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
            <script type="text/javascript">
	            function doDelete() {
	            	//判断是否删除显示的详情所对应的退货单
	            	var dd = 0;
	            	var row=$.map($("#tb_departments").bootstrapTable('getSelections'),function(row){
	            		return row ;
	            	});
	            	if (row.length == 0) {
	            		toastr.warning('请至少选择一条数据!');
	            	}else{
	            		var ids="";
	            		for(var i=0;i<row.length;i++){
	            			if(row[0].remark6 != 0){
	                			
	            			}else{
		            			ids+=","+row[i].id;
		            			if(row[i].plannumber == $.trim($('#id').val())){
		            				dd++;
		            			}
	            			}
	            		}
	            	
	            		ids = ids.substr(1,ids.length-1);
	            		//询问框
	            		Ewin.confirm({ message: "确认要删除选择的数据吗"}).on(function (e) {
	            	       if (!e) {
	            	         return;
	            	       } 
	            	    	var url = "${pageContext.request.contextPath }/plan/delete.do";
	            		    $.post(url, "ids="+ids, function(data) {
	            				if (data == 1) {
	            					toastr.success('删除成功');
	            					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	            						$('#tb_departments').bootstrapTable('refresh');
	            						if(dd>0){
		            						$("#id").val(0);
		        	                    	$('#tb_tables').bootstrapTable('refresh');
	            						}
	            					},2000);
	            				} else if (data == 2) {
	            					toastr.warning('该信息已删除!');
	            					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	            						$('#tb_departments').bootstrapTable('refresh'); 
	            					},2000); 
	            				} else {
	            					toastr.error('删除失败');
	            					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	            						$('#tb_departments').bootstrapTable('refresh'); 
	            					},2000);
	            				}
	            			}); 
	            	    }); 
	            	}
	            }
            </script>
            &nbsp;
            <button id="btn_depty" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-phone" aria-hidden="true"></span>审批
            </button>
           <!--  <button id="btn_edit1" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>撤销审批
            </button> -->
            <%--<button id="btn_delete1" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-tasks" aria-hidden="true"></span>导出
            </button>--%>
            <%--<button id="btn_delete2" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-send" aria-hidden="true"></span>关闭
            </button>--%>
        </div>
     
        <table id="tb_departments"></table>
        <input type="hidden" id="id" value="0">
        <table id="tb_tables"></table>
    </div>
</body>
</html>